package com.qf.filter;

import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 全局认证
 * 令牌不合法，拒绝访问  （jwt，123）
 *
 * 令牌合法，放行
 */
@Component
public class AccessGlobalFilter implements GlobalFilter, Ordered {


    @Value("${source.white}")
    private String URLS;
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getPath().toString();

        String jwt = request.getHeaders().getFirst("jwt");

        HttpCookie token = request.getCookies().getFirst("token");


        //获取白名单
        String[] urlArr = URLS.split(",");

        for (String url : urlArr) {
            if(Pattern.matches(url,path)){
                return chain.filter(exchange);
            }
        }


        if (StringUtils.isEmpty(token)) {

            //拒绝访问，给用户反馈
            Map res = new HashMap(){{
                put("msg","非法令牌");
            }};
            return response(response,res);
        }
        

        try {
            //验证token
            JwtParser parser = Jwts.parser();
            parser.setSigningKey("QIANfeng6666"); //解析token的SigningKey必须和生成token时设置密码一致
            //如果token正确（密码正确，有效期内）则正常执行，否则抛出异常
            Jws<Claims> claimsJws = parser.parseClaimsJws(String.valueOf(token));
            io.jsonwebtoken.Claims body = claimsJws.getBody();  //获取token中用户数据
            String subject = body.getSubject(); //获取生成token设置的subject
            String userId = body.get("userId", String.class); //获取生成token时存储的Claims的map中的值
            ServerHttpRequest newRequset = request.mutate().header("userId", userId).build();
            ServerWebExchange newEx = exchange.mutate().request(newRequset).build();
            return chain.filter(newEx);
            
        }catch (ExpiredJwtException e){
            return new ResultVO(ResStatus.NO,"登录过期，请重新登录！",null);
        }catch (UnsupportedJwtException e){
            return new ResultVO(ResStatus.NO,"Token不合法！",null);
        }catch (Exception e){
            return new ResultVO(ResStatus.NO,"请重新登录！",null);
        }
    }


    //决定过滤器的执行顺序，数值越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }


    //响应
        private Mono<Void>  response(ServerHttpResponse response,Object msg){
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            String resJson = JSONUtil.toJsonStr(msg);
            DataBuffer dataBuffer = response.bufferFactory().wrap(resJson.getBytes());
            return response.writeWith(Flux.just(dataBuffer));//响应json数据
        }


    public static void main(String[] args) {

        boolean matches = Pattern.matches("/homepage/(.*)", "/homepage/now");
        System.out.println(matches);
    }
}
